package com.apes.fn.scm.purchase.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.fn.scm.purchase.repository.ProductPriceDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.repository.ProductStockDao;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by lishikun on 2021/8/4 11:37
 */
@Service("productPriceService")
public class ProductPriceService extends DomainService {

    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private ProductPriceDao productPriceDao;
    @Autowired
    private ProductRepository productRepository;


    public JSONObject findProductPrice(SimpleRequest request) {
        // 条件
        JSONObject param = new JSONObject();
        List<Map> filters = request.get("condition");
        for (Map filter : filters) {
            param.put(filter.get("field").toString(), filter.get("value"));
        }
        List productIds = new ArrayList<>();
        JSONArray inquiryPools = new JSONArray();
        productIds.addAll(param.getJSONArray("PRODUCT_ID"));
        List<Product> productList = productRepository.findAllById(productIds);
        Iterator<Product> iterator = productList.iterator();
        JSONObject constructResponse = new JSONObject();
        while (iterator.hasNext()){
            Product product = iterator.next();
            param.put("product", MapUtil.mapped(product));
            Dept dept = deptRepository.findOne(param.getString("DEPT_ID"));
            param.put("OLD_DEPT", dept.getOrigin());
            JSONArray inquiryPool = productPriceDao.getInquiryPool(param);
            JSONObject warranty = getWarranty(param);
            Integer productStock = getProductStock(param);
            constructResponse.putAll(constructResponse(inquiryPool, warranty, productStock, param, product, productList, inquiryPools));

        }
        return constructResponse;
    }

    /**
     * 构建返回数据
     */
    private JSONObject constructResponse(JSONArray inquiryPool, JSONObject warranty, Integer productStock, JSONObject param, Product product, List<Product> productList, JSONArray inquiryPools) {
        JSONObject response = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("STOCK_QTY", productStock);
        jsonObject.put("Z001", warranty.getDoubleValue("Z001"));
        jsonObject.put("Z002", warranty.getDoubleValue("Z002"));
        jsonObject.put("Z003", warranty.getDoubleValue("Z003"));
        jsonObject.put("Z004", warranty.getDoubleValue("Z004"));
        jsonObject.put("PRODUCT", MapUtil.mapper("ID", param.getJSONObject("product").getString("id"),
                "NAME", param.getJSONObject("product").getString("name")));

        for (Object o : inquiryPool) {
            JSONObject object = (JSONObject) o;
            param.put("SUPPLIER_ID", object.getString("GYSID"));
            JSONObject xs51 = getXS51(param, product, inquiryPool);
            object.putAll(jsonObject);
            object.putAll(xs51);
        }
        if (inquiryPool.size() <= productList.size()) {
            inquiryPool.add(jsonObject);
            JSONObject xs51 = getXS51(param, product, inquiryPool);
            jsonObject.putAll(xs51);
        }

        inquiryPools.addAll(inquiryPool);
        response.put("total", inquiryPool.size());
        response.put("pages", 1);
        response.put("size", inquiryPool.size());
        response.put("elements", inquiryPool.size());
        response.put("content", inquiryPools);
        return response;
    }


    /**
     * 获取质保期数据
     *
     * @param param
     */
    private JSONObject getWarranty(JSONObject param) {
        Map map = new HashMap();
        map.put("PRODUCT_ID", param.getJSONObject("product").getString("id"));
        map.put("BRAND_ID", param.getJSONObject("product").getJSONObject("brand").getString("id"));
        map.put("CLASSIFY_ID", param.getJSONObject("product").getJSONObject("classify").getString("id"));
        map.put("SYS_RQ", new Date());
        map.put("conditionStrategyId", "CX_ZBQWH");
        map.put("SUPPLIER_ID", "");
        return JSONObject.parseObject(this.invoke("condition.execConditionStrategy", map).toString());
    }


    /**
     * 获取商品库存数据
     *
     * @param param
     */
    private Integer getProductStock(JSONObject param) {
        JSONArray allStockByProduct = SpringManager.getBean(ProductStockDao.class).getAllStockByProduct(param);
        return allStockByProduct.getJSONObject(0).getIntValue("STOCK_QTY");
    }

    private JSONObject getXS51(JSONObject param, Product product, JSONArray inquiryPool) {
        Dept dept = null;
        JSONObject result = new JSONObject();
        if (param.get("DEPT_ID") != null) {
            dept = deptRepository.findOne(param.getString("DEPT_ID"));
        }

        PartyRole platform = dept != null ? SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, dept, product) : null;
        JSONObject content = null;
        if (param.get("carLicense") != null) {
            JSONObject filter = new JSONObject();
            filter.put("value", param.getString("carLicense"));
            filter.put("field", "carLicense");
            filter.put("operator", "EQ");
            List list = new ArrayList();
            list.add(filter);
            Map o = (Map) invoke("fn.practicalFunction.smartAccessories.find", MapUtil.mapper("condition", list, "size", 20, "page", 0));
            content = ((JSONArray) o.get("content")).getJSONObject(0);
        } else {
            result.put("SYS_NO_CHECK", "CAR_LICENSE");
        }

        result.put("conditionStrategyId", "XS51");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "1");
        result.put("DEPT_ID", null);
        result.put("CAR_SERVICE_LEVEL_ID", param.getString("SERVICE_LEVEL"));
        result.put("PUR_COMPANY_ID", platform != null ? platform.getId() : null);
        result.put("PRODUCT_ID", product.getId());
        result.put("PRODUCT_UOM_ID", product.getUom().getId());
        result.put("BRAND_ID", product.getBrand() != null ? product.getBrand().getId() : null);
        result.put("QUALITY", product.getBrand().getQuality() != null ? product.getBrand().getQuality().getCode() : null);
        result.put("CLASSIFY_ID", product.getClassify().getId());
        result.put("SAL_COMPANY_ID", dept != null ? dept.getCompany().getId() : null);
        result.put("ACCESS_PROVIDER_ID", content != null ? content.getJSONObject("customer").getJSONObject("userRole").getString("id") : null);
        result.put("BUSINESS_CIRCLE_ID", dept != null ? SpringManager.getBean(StoreService.class).findBusinessCircleByDept(dept).getId() : null);
        result.put("PHONE_NUMBER", content != null ? content.getString("mobile") : null);
        result.put("VIP_IDENTITY_ID", content != null ? content.getJSONObject("customer").getJSONObject("userRole").getString("id") : null);
        result.put("VIP_LEVEL_ID", content != null ? content.getJSONObject("customer").get("level") : null);
        result.put("CAR_LICENSE", content != null ? content.get("carLicense") : null);

        // 合作类型
        result.put("COOPERATION_TYPE", param.get("CROSSIC_ID"));
        result.put("CUSTOMER_ID", null);
        result.put("SUPPLIER_ID", param.getString("SUPPLIER_ID"));
        result.put("OPERATION", dept != null ? dept.getCompany().getParty().getCorporate().getOperation().getCode() : null);
        JSONObject invoke = JSONObject.parseObject(this.invoke("condition.execConditionStrategy", result).toString());

        JSONObject response = new JSONObject();
        response.put("PURCHAS_ECCOST_NO_TAX", invoke.get("P001"));
        response.put("PURCHAS_ECCOST_TAX", invoke.get("P904"));
        response.put("SALE_PRICE", invoke.get("P004"));
        response.put("E_COMMERCE_PRICE", invoke.get("S210"));
        response.put("MINIMUM_PRICE", invoke.get("S903"));
        response.put("SHOP_MANAGER_PRICE", invoke.get("S802"));
        response.put("DIRECTOR_PRICE", invoke.get("S803"));
        response.put("ORIGINAL_PRICE", invoke.get("Z002"));
        return response;
    }

    /**
     * 根据系统变量取价格
     *
     * @return
     */
    public JSONObject getPrice(SimpleRequest request) {
        JSONObject param = request.getJO();
        String companyId = param.getString("HTGSID");//取采购合同的公司id
        String productId = param.getString("SPID");
        String supplierId = param.getString("GYSID");
        String type = param.getString("TYPE");
        Product product = productRepository.findOne(productId); // 查询商品

        // 获取价格
        JSONObject condition = getCondition(companyId, supplierId, product, "", type);
        Object obj = this.invoke("condition.execConditionStrategy_trans", condition);
        JSONObject getJG = new JSONObject(MapUtil.mapped(obj));

        double gP901 = getJG.getDoubleValue("P901");
        double gP904 = getJG.getDoubleValue("P904");

        double nakedPrice = "1007".equals(param.getString("CGZZID")) ? gP901 : gP904;
        if (nakedPrice == 0 && "product".equals(product.getType())) {
            throw new RuntimeException("采购价格文件不能为0！商品编码：" + productId + " 供应商：" + supplierId);
        }
        getJG.put("purchasePrice", nakedPrice);
        return getJG;
    }

    private JSONObject getCondition(String companyId, String supplierId, Product product, String carLicense, String type){
        JSONObject resultCondition = new JSONObject();
        if ("saleReturnCost".equals(type)) {
            resultCondition =  getPurchaseReturnPrice(companyId, supplierId, product, carLicense);
        }

        // 兼容之前没有值的情况
        if ("".equals(type)) {
            resultCondition = getPurchasePrice(companyId, supplierId, product, carLicense);
        }
        return resultCondition;
    }

    /**
     * 获取采购价格策略--新系统
     *
     * @param companyId  采购平台公司编码
     * @param supplierId 供应商编码
     * @param product  商品
     * @param carLicense 车牌号码
     * @return
     */
    private JSONObject getPurchasePrice(String companyId, String supplierId, Product product, String carLicense) {
        JSONObject condi = new JSONObject();

        condi.put("SYS_RQ", new Date());
        condi.put("conditionStrategyId", "CG02");
        condi.put("COMPANY_ID", companyId);
        condi.put("SUPPLIER_ID", supplierId);
        condi.put("PRODUCT_ID", product.getId());
        condi.put("BRAND_ID", product.getBrand().getId());
        condi.put("CLASSIFY_ID", product.getClassify().getId());
        if (!StringUtils.isEmpty(carLicense)) {
            condi.put("CAR_LICENSE", carLicense);
        } else {
            condi.put("SYS_NO_CHECK", "CAR_LICENSE");
        }
        return condi;
    }

    /**
     * 无原单销售退回时，找价格
     *
     * @param companyId  公司编码
     * @param supplierId 供应商编码
     * @param product    商品
     * @param carLicense 车牌号码
     * @return condition
     */
    private JSONObject getPurchaseReturnPrice(String companyId, String supplierId, Product product, String carLicense) {
        JSONObject condition = new JSONObject();
        condition.put("SYS_RQ", new Date());
        condition.put("conditionStrategyId", "CG02");
        condition.put("COMPANY_ID", companyId);
        condition.put("PRODUCT_ID", product.getId());
        condition.put("BRAND_ID", product.getBrand().getId());
        condition.put("CLASSIFY_ID", product.getClassify().getId());
        if (!StringUtils.isEmpty(carLicense)) {
            condition.put("CAR_LICENSE", carLicense);
        } else {
            condition.put("SYS_NO_CHECK", "A00000".equals(supplierId) ? "CAR_LICENSE,SUPPLIER_ID" : "CAR_LICENSE");
        }
        if (!"A00000".equals(supplierId)) {
            condition.put("SUPPLIER_ID", supplierId);
        }
        return condition;
    }

}
